package com.example.inventorywarningdemo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.inventorywarningdemo.entity.Order;
import com.example.inventorywarningdemo.entity.Store;
import com.example.inventorywarningdemo.mapper.OrderMapper;
import com.example.inventorywarningdemo.mapper.StoreMapper;
import com.example.inventorywarningdemo.service.StoreService;

import com.example.inventorywarningdemo.util.MailUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

/**
 * @author Survive
 * @date 2025/3/11
 * @description TODO  店铺实现类
 */
@Service
@RequiredArgsConstructor
public class StoreServiceImpl implements StoreService {
    private final StoreMapper storeMapper;
    private final OrderMapper orderMapper;
    private final MailUtil mailUtil;

    @Override
    public void checkDailySales() {
        // 获取所有店铺信息
        List<Store> stores = storeMapper.selectList(null);

        stores.forEach(store -> {
            // 计算当日销售额
            BigDecimal actualSales = calculateDailySales(store.getId());

            // 比较预警值
            if (actualSales.compareTo(store.getWarningThreshold()) < 0) {
                store.setDailySales(actualSales);  // 动态设置销售额用于邮件显示
                mailUtil.sendAlertEmail(store);
            }
        });
    }
    private BigDecimal calculateDailySales(Long storeId) {
        QueryWrapper<Order> query = new QueryWrapper<>();
        query.select("IFNULL(SUM(amount), 0) as total")
                .eq("store_id", storeId)
                .apply("DATE(order_time) = CURDATE()");

        Map<String, Object> result = orderMapper.selectMaps(query).get(0);
        return new BigDecimal(result.get("total").toString());
    }
}